package com.boomsecret.zookeeper;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * Created by wangjinliang on 2018/8/6.
 */
public class CuratorDemo {

    // 重试时间间隔
    private static final int RETRY_TIME = 1000;
    // 重试次数
    private static final int RETRY_TIMES = 3;

    public static void main(String[] args) throws Exception {
        for (int index = 0; index < 10; index ++) {
            new LockTask(index).start();
            Thread.sleep(800);
        }
    }

    static class LockTask extends Thread {
        private int index;

        LockTask(int index) {
            this.index = index;
        }

        @Override
        public void run() {
            // 操作失败重试机制
            RetryPolicy retryPolicy = new ExponentialBackoffRetry(RETRY_TIME, RETRY_TIMES);
            // 创建Curator客户端
            CuratorFramework client = CuratorFrameworkFactory.newClient("182.92.234.232:2181", retryPolicy);
            // 开始
            client.start();

            /**
             * 这个类是线程安全的，一个JVM创建一个就好
             * lockRoot 为锁的根目录，我们可以针对不同的业务创建不同的根目录
             */
//            final InterProcessMutex lock = new InterProcessMutex(client, "/lockRoot"); // 公平锁
            final InterProcessMutex lock = new InterProcessMutex(client, "/lockRoot", new NoFairLockDriver()); // 非公平锁
            try {
                // 阻塞方法，获取不到锁线程会挂起。
                System.out.println(index + "打算获取锁");
                lock.acquire();
                Thread.sleep(10000);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    lock.release();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println(index + "释放锁");
                client.close();
            }
        }
    }
}
